package cs2340.g21.wms;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * A wrapper class that allows bitmaps to be serialized
 */
public class SerializableBitmap implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4446075850909205048L;

	private Bitmap bitmap;
	
    private static final int NO_IMAGE = -1;

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap image) {
        bitmap = image;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        if (bitmap != null) {
        	final ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            final byte[] imageByteArray = stream.toByteArray();
            out.writeInt(imageByteArray.length);
            out.write(imageByteArray, 0, imageByteArray.length);
        } else {
            out.writeInt(NO_IMAGE);
        }
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{

        final int length = in.readInt();

        if (length != NO_IMAGE) {
        	ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int b;
            while((b = in.read()) != -1)
                byteStream.write(b);
            byte bitmapBytes[] = byteStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
        }
    }
}
